<template>
  <div class="confirm-container">
    <!-- 步骤指示器 -->
    <div class="steps-indicator">
      <div class="step active">
        <div class="step-circle">预约服务</div>
      </div>
      <div class="step-line active"></div>
      <div class="step">
        <div class="step-circle">支付订单</div>
      </div>
      <div class="step-line"></div>
      <div class="step">
        <div class="step-circle">门店服务</div>
      </div>
    </div>

    <!-- 门店信息 -->
    <div class="store-info">
      <div class="store-header">
        <image
          class="store-icon"
          :src="detail.merchantImgs.img.split(',')[0]"
          mode="aspectFill"
        ></image>
        <div class="store-details">
          <div class="store-name">{{ detail.name }}</div>
          <div class="store-address">{{ detail.address }}</div>
        </div>
      </div>
    </div>

    <!-- 用户信息 -->
    <div class="user-info">
      <div class="info-item">
        <text class="info-label">👤</text>
        <text class="info-text">{{
          detail.merchantVerification.director
        }}</text>
      </div>
      <div class="info-item">
        <text class="info-label">📱</text>
        <text class="info-text">{{ detail.merchantVerification.mobile }}</text>
      </div>
    </div>

    <!-- 立即预约 -->
    <div class="appointment-section" @click="showAppointmentModal">
      <div class="appointment-header">
        <text class="section-title">立即预约</text>
        <text class="arrow">›</text>
      </div>
      <text v-if="selectedTime" class="selected-time">{{ selectedTime }}</text>
    </div>

    <!-- 车辆信息 -->
    <div class="car-info" @click="goToChooseCar">
      <div class="info-item">
        <text class="info-label">🚗</text>
        <text class="info-text" v-if="theCar"
          >{{ theCar.brandName }}:{{ theCar.carType.name }}/{{
            theCar.carNum
          }}</text
        >
      </div>
      <text class="arrow">›</text>
    </div>

    <!-- 服务产品 -->
    <div class="services-section">
      <div class="section-header">
        <text class="section-title">服务产品</text>
        <text class="selected-count"
          >共选择{{ services.length }}项服务产品</text
        >
      </div>
      <div
        class="service-item"
        v-for="(service, index) in services"
        :key="index"
      >
        <text class="service-name">{{ service.name }}</text>
        <text class="service-price">¥{{ service.presentPrice }}</text>
      </div>
    </div>

    <!-- 代金券/优惠券 -->
    <div class="coupon-section">
      <div class="coupon-header" @click="goToChooseCoupon">
        <text class="section-title">代金券/优惠券</text>
        <text class="coupon-status">{{ coupon ? coupon.name : "暂无" }} ›</text>
      </div>
    </div>

    <!-- 备注信息 -->
    <div class="remark-section">
      <text class="section-title">备注信息</text>
      <textarea class="remark-input" placeholder="请输入备注信息"></textarea>
    </div>

    <!-- 底部提交订单 -->
    <div class="bottom-bar">
      <div class="total-section">
        <text class="total-label">合计：</text>
        <text class="total-price">¥{{ totalPrice }}</text>
      </div>
      <button class="submit-btn" @click="submitOrder">提交订单</button>
    </div>

    <!-- 客服悬浮按钮 -->
    <div class="customer-service" @click="showCustomerService">
      <text class="service-icon">🎧</text>
    </div>

    <!-- 预约时间弹窗 -->
    <div
      class="modal-overlay"
      v-if="showAppointment"
      @click="closeAppointmentModal"
    ></div>
    <div class="appointment-modal" v-if="showAppointment">
      <div class="modal-header">
        <text class="modal-title">预约时间</text>
        <text class="modal-subtitle">({{ formatCurrentDate }})</text>
      </div>
      <div class="appointment-content">
        <!-- 左侧日期滑动选择器 -->
        <div class="date-section">
          <div class="section-title">立即预约</div>
          <picker
            mode="selector"
            :range="dateOptions"
            :value="selectedDateIndex"
            @change="onDateChange"
          >
            <div class="picker-trigger">
              <text class="selected-date" v-if="selectedDate">{{
                selectedDate.date
              }}</text>
              <text class="placeholder" v-else>选择日期</text>
              <text class="arrow">›</text>
            </div>
          </picker>
        </div>

        <!-- 右侧时间滑动选择器 -->
        <div class="time-section">
          <picker
            mode="selector"
            :range="timeSlots"
            :value="selectedTimeSlotIndex"
            @change="onTimeChange"
          >
            <div class="picker-trigger">
              <text class="selected-time" v-if="selectedTimeSlot">{{
                selectedTimeSlot.time
              }}</text>
              <text class="placeholder" v-else>选择时间</text>
              <text class="arrow">›</text>
            </div>
          </picker>
        </div>
      </div>
      <div class="modal-footer">
        <button class="cancel-btn" @click="closeAppointmentModal">取消</button>
        <button
          class="confirm-btn"
          :disabled="!selectedDate || !selectedTimeSlot"
          @click="confirmAppointment"
        >
          确定
        </button>
      </div>
    </div>

    <!-- 客服弹窗 -->
    <div
      class="modal-overlay"
      v-if="showServiceModal"
      @click="closeServiceModal"
    ></div>
    <div class="service-modal" v-if="showServiceModal">
      <div class="phone-number">{{ detail.merchantVerification.mobile }}</div>
      <div class="action-buttons">
        <button class="call-btn" @click="makePhoneCall">呼叫</button>
        <button class="cancel-btn" @click="closeServiceModal">取消</button>
      </div>
    </div>
  </div>
</template>

<script>
import request from "@/utils/request.js";
import {wxPay} from "@/utils/wxPay.js";
export default {
  components: {},
  data() {
    return {
      coupon: {},
      theCar: {},
      detail: {},
      servies: {},
      // 原价
      originalPrice: 0,

      dateOptions: [], // 日期选项（字符串数组供picker使用）
      timeSlots: [], // 时间选项（字符串数组供picker使用）
      showAppointment: false,
      showServiceModal: false,
      selectedTime: "",
      selectedDate: null, // 选中的日期对象
      selectedTimeSlot: null, // 选中的时间对象
      selectedDateIndex: 0, // 选中的日期索引
      selectedTimeSlotIndex: 0, // 选中的时间索引
      dateObjects: [], // 日期对象数组
      timeObjects: [], // 时间对象数组
    };
  },
  computed: {
    // 格式化当前日期显示
    formatCurrentDate() {
      const date = new Date();
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      const day = date.getDate();
      const hours = date.getHours().toString().padStart(2, "0");
      const minutes = date.getMinutes().toString().padStart(2, "0");
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    },
  },
  methods: {
    // 跳转选择优惠券页面
    goToChooseCoupon() {
      uni.navigateTo({
        url: "/pages/maintenance/chooseCoupon/chooseCoupon",
      });
    },
    // 生成未来几天的日期选项
    generateDateOptions() {
      const dateStrings = [];
      const dateObjects = [];
      const today = new Date();

      // 生成未来7天的日期选项
      for (let i = 0; i < 7; i++) {
        const date = new Date(today);
        date.setDate(today.getDate() + i);

        // 格式化日期
        const month = (date.getMonth() + 1).toString().padStart(2, "0");
        const day = date.getDate().toString().padStart(2, "0");

        // 生成日期显示文本
        let dateText = `${month}月${day}日`;
        if (i === 0) {
          dateText += "（今天）";
        } else if (i === 1) {
          dateText += "（明天）";
        } else if (i === 2) {
          dateText += "（后天）";
        } else {
          // 对于其他日期，显示星期几
          const weekDays = [
            "周日",
            "周一",
            "周二",
            "周三",
            "周四",
            "周五",
            "周六",
          ];
          dateText += `（${weekDays[date.getDay()]}）`;
        }

        dateStrings.push(dateText);
        dateObjects.push({
          id: i + 1,
          date: dateText,
          fullDate: `${date.getFullYear()}-${month}-${day}`,
        });
      }

      this.dateOptions = dateStrings;
      this.dateObjects = dateObjects;
    },

    // 生成整点时间选项，基于门店营业时间
    generateTimeSlots() {
      const timeStrings = [];
      const timeObjects = [];

      // 默认营业时间范围
      let startHour = 9;
      let endHour = 21;

      // 尝试从门店信息中提取营业时间
      if (this.detail && this.detail.startTime && this.detail.endTime) {
        try {
          // 解析开始时间
          const startTime = new Date(this.detail.startTime);
          startHour = startTime.getHours();

          // 解析结束时间
          const endTime = new Date(this.detail.endTime);
          endHour = endTime.getHours();

          // 添加基本验证，确保时间范围合理
          if (
            startHour < 0 ||
            startHour > 23 ||
            endHour < 0 ||
            endHour > 23 ||
            startHour >= endHour
          ) {
            // 如果营业时间无效，使用默认值
            startHour = 9;
            endHour = 21;
          }
        } catch (error) {
          console.error("解析营业时间出错:", error);
          // 出错时使用默认值
          startHour = 9;
          endHour = 21;
        }
      }

      // 根据营业时间生成时间选项
      for (let hour = startHour; hour <= endHour; hour++) {
        const timeText = `${hour}:00`;
        timeStrings.push(timeText);
        timeObjects.push({
          id: hour,
          time: timeText,
        });
      }

      this.timeSlots = timeStrings;
      this.timeObjects = timeObjects;
    },

    // 显示预约时间弹窗
    showAppointmentModal() {
      // 重置选择状态
      this.selectedDate = null;
      this.selectedTimeSlot = null;

      // 生成日期和时间选项
      this.generateDateOptions();
      this.generateTimeSlots();

      this.showAppointment = true;
    },

    // 关闭预约时间弹窗
    closeAppointmentModal() {
      this.showAppointment = false;
    },

    // 选择日期事件（picker组件使用）
    onDateChange(e) {
      const index = e.detail.value;
      this.selectedDateIndex = index;
      this.selectedDate = this.dateObjects[index];
    },

    // 选择时间事件（picker组件使用）
    onTimeChange(e) {
      const index = e.detail.value;
      this.selectedTimeSlotIndex = index;
      this.selectedTimeSlot = this.timeObjects[index];
    },

    // 确认预约
    confirmAppointment() {
      if (this.selectedDate && this.selectedTimeSlot) {
        this.selectedTime = `${this.selectedDate.date} ${this.selectedTimeSlot.time}`;
      }
      this.showAppointment = false;
    },

    // 显示客服弹窗
    showCustomerService() {
      this.showServiceModal = true;
    },

    // 关闭客服弹窗
    closeServiceModal() {
      this.showServiceModal = false;
    },

    // 拨打电话
    makePhoneCall() {
      uni.makePhoneCall({
        phoneNumber: this.detail.merchantVerification.mobile,
      });
      this.showServiceModal = false;
    },

    // 跳转到车型选择页面
    goToChooseCar() {
      uni.navigateTo({
        url: "../chooseCar/chooseCar",
      });
    },

    // 提交订单
    submitOrder() {
      // 检查是否已选择预约时间
      if (!this.selectedTime) {
        uni.showToast({
          title: "请选择预约时间",
          icon: "none",
        });
        return;
      }
      if (!this.theCar) {
        uni.showToast({
          title: "请选择车型",
          icon: "none",
        });
      }
      if (
        this.coupon != null &&
        this.coupon.type == 1 &&
        this.originalPrice < this.coupon.preferentialMoney
      ) {
        uni.showToast({
          title: "优惠券使用不合法",
          icon: "none",
        });
        return;
      }
      wxPay({
        couponId: this.coupon.id, //优惠券id 有就按时填写，没有就写-1 后端有处理
        carId: this.theCar.id, //汽车id 有就按时填写，没有填写-1 后端有处理
        payPrice: this.totalPrice, //这个是支付的价格，填写真实支付价格
        serviceIds: this.services.map((service) => service.id), // 订单的服务id,也就是该订单选了服务详情表中的哪些订单
        serviceTypeID: 2, // 服务类型id 1-洗车 2-维修 3-保养
        serviceImg: "", // 可选参数 有就传递 没就默认值
      });
      // request({
      //   url: "/pyh/order/addMaintenanceOrder",
      //   method: "POST",
      //   data:{
      //     carInfo: this.theCar,
      //     coupon: this.coupon,
      //     reservationTime: this.selectedDate && this.selectedTimeSlot ? `${this.selectedDate.fullDate} ${this.selectedTimeSlot.time}` : '',
      //     orderUserMerchant:{
      //       merchantId: this.detail.merchantVerification.id,
      //       orderContent: JSON.stringify(this.services),
      //     },

      //     serviceDetails: this.services
      //   },
      //   success: (res) => {
      //     if (res.code == 200) {
      //       uni.showToast({
      //         title: "订单提交成功",
      //         icon: "success",
      //       });

      //     } else {
      //       uni.showToast({
      //         title: res.msg,
      //         icon: "none",
      //       });
      //     }
      //   },
      // });

      // 跳转到支付结果页面
      // uni.navigateTo({
      //   url: "../paymentResult/paymentResult",
      // });
    },
  },
  computed: {
    // 计算总价
    totalPrice() {
      let yuan = this.services.reduce(
        (acc, service) => acc + service.presentPrice,
        0
      );
      if (this.coupon && this.coupon.type == 1) {
        return yuan - this.coupon.preferentialMoney;
      } else if (this.coupon && this.coupon.type == 0) {
        return yuan * this.coupon.discount;
      }
      return yuan;
    },
  },
  // 页面周期函数--监听页面加载
  onLoad() {
    this.detail = uni.getStorageSync("detail");
    this.services = uni.getStorageSync("selectedServices");
    // 计算总价
    // this.totalPrice = this.services.reduce((acc, service) => acc + service.presentPrice, 0);
    this.originalPrice = this.services.reduce(
      (acc, service) => acc + service.presentPrice,
      0
    );
    console.log("detail:", this.detail);
    console.log("services:", this.services);

    // 日期和时间选项将在打开弹窗时动态生成
  },
  // 页面周期函数--监听页面初次渲染完成
  onReady() {},
  // 页面周期函数--监听页面显示(not-nvue)
  onShow() {
    this.theCar = uni.getStorageSync("theCar");
    console.log("theCar:", this.theCar);
    this.coupon = uni.getStorageSync("coupon");
    console.log("coupon:", this.coupon);
  },
};
</script>

<style scoped>
.confirm-container {
  padding-bottom: 80rpx;
  position: relative;
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 步骤指示器 */
.steps-indicator {
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 30rpx 0;
  background-color: #fff;
  margin-bottom: 20rpx;
}

.step {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.step-circle {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  background-color: #e0e0e0;
  color: #666;
  font-size: 24rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
}

.step.active .step-circle {
  background-color: #1989fa;
  color: #fff;
}

.step-line {
  width: 100rpx;
  height: 4rpx;
  background-color: #e0e0e0;
  flex: 1;
  max-width: 100rpx;
}

.step-line.active {
  background-color: #1989fa;
}

/* 通用样式 */
.store-info,
.user-info,
.appointment-section,
.car-info,
.services-section,
.coupon-section,
.remark-section {
  background-color: #fff;
  margin-bottom: 20rpx;
  padding: 30rpx;
}

.section-title {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.info-label {
  font-size: 32rpx;
  margin-right: 20rpx;
}

.info-text {
  font-size: 32rpx;
  color: #333;
}

/* 车辆信息 */
.car-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.car-info:active {
  background-color: #f0f0f0;
}

.car-info .info-item {
  flex: 1;
  margin-bottom: 0;
}

/* 门店信息 */
.store-header {
  display: flex;
  align-items: center;
}

.store-icon {
  width: 100rpx;
  height: 100rpx;
  border-radius: 10rpx;
  margin-right: 20rpx;
}

.store-details {
  flex: 1;
}

.store-name {
  font-size: 34rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 10rpx;
}

.store-address {
  font-size: 28rpx;
  color: #666;
}

/* 立即预约 */
.appointment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.arrow {
  font-size: 40rpx;
  color: #999;
}

.selected-time {
  font-size: 28rpx;
  color: #666;
  margin-top: 10rpx;
  display: block;
}

/* 服务产品 */
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.selected-count {
  font-size: 28rpx;
  color: #666;
}

.service-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  border-top: 1rpx solid #f0f0f0;
}

.service-name {
  font-size: 32rpx;
  color: #333;
}

.service-price {
  font-size: 32rpx;
  color: #f56c6c;
  font-weight: 500;
}

/* 代金券 */
.coupon-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.coupon-status {
  font-size: 28rpx;
  color: #666;
}

/* 备注信息 */
.remark-input {
  width: 100%;
  height: 160rpx;
  margin-top: 20rpx;
  padding: 20rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 10rpx;
  font-size: 32rpx;
  color: #333;
  box-sizing: border-box;
}

/* 底部提交订单 */
.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background-color: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 30rpx;
  border-top: 1rpx solid #e0e0e0;
  z-index: 100;
}

.total-section {
  display: flex;
  align-items: center;
}

.total-label {
  font-size: 32rpx;
  color: #333;
}

.total-price {
  font-size: 36rpx;
  color: #f56c6c;
  font-weight: 600;
}

.submit-btn {
  width: 200rpx;
  height: 70rpx;
  background-color: #f56c6c;
  color: #fff;
  border: none;
  border-radius: 35rpx;
  font-size: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 客服悬浮按钮 */
.customer-service {
  position: fixed;
  bottom: 120rpx;
  right: 30rpx;
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  background-color: #1989fa;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 99;
  box-shadow: 0 4rpx 20rpx rgba(25, 137, 250, 0.3);
}

.service-icon {
  font-size: 48rpx;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 101;
}

.appointment-modal,
.service-modal {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  border-radius: 30rpx 30rpx 0 0;
  z-index: 102;
  padding: 30rpx;
}

.modal-header {
  text-align: center;
  margin-bottom: 30rpx;
  position: relative;
}

/* 弹窗头部样式 */
.modal-header {
  text-align: center;
  margin-bottom: 30rpx;
  position: relative;
}

.modal-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #333;
}

.modal-subtitle {
  font-size: 28rpx;
  color: #666;
  margin-left: 10rpx;
}

/* 预约内容区域 */
.appointment-content {
  display: flex;
  margin-bottom: 30rpx;
  height: 400rpx;
}

/* 左侧日期选择 */
.date-section {
  flex: 1;
  border-right: 1rpx solid #f0f0f0;
  padding-right: 20rpx;
}

.section-title {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 20rpx;
}

.date-scroll {
  height: calc(100% - 60rpx);
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
}

.date-option {
  padding: 25rpx 0;
  text-align: center;
  border-bottom: 1rpx solid #f0f0f0;
}

.date-option.selected {
  background-color: #f0f8ff;
  color: #1989fa;
  font-weight: 500;
}

/* 右侧时间选择 */
.time-section {
  flex: 1;
  padding-left: 20rpx;
}

.time-scroll {
  height: 100%;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
}

.time-option {
  padding: 25rpx 0;
  text-align: center;
  border-bottom: 1rpx solid #f0f0f0;
}

.time-option.selected {
  background-color: #f0f8ff;
  color: #1989fa;
  font-weight: 500;
}

/* 通用样式 */
.check-icon {
  font-size: 36rpx;
  color: #1989fa;
  font-weight: bold;
  margin-left: 20rpx;
}

.date {
  font-size: 32rpx;
  color: #333;
}

/* 确认按钮禁用样式 */
.confirm-btn:disabled {
  background-color: #ccc;
  color: #fff;
}

.modal-footer {
  display: flex;
  justify-content: space-between;
  margin-top: 30rpx;
}

.cancel-btn,
.confirm-btn,
.call-btn {
  flex: 1;
  height: 80rpx;
  border-radius: 40rpx;
  font-size: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #666;
  margin-right: 20rpx;
  border: none;
}

.confirm-btn {
  background-color: #1989fa;
  color: #fff;
  border: none;
}

.call-btn {
  background-color: #f56c6c;
  color: #fff;
  border: none;
  margin-right: 20rpx;
}

/* 客服弹窗样式 */
.phone-number {
  text-align: center;
  font-size: 36rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 40rpx;
}

.action-buttons {
  display: flex;
  justify-content: space-between;
}
</style>
